package com.atguigu.srb.core.controller.api;


import com.alibaba.fastjson.JSON;
import com.atguigu.common.result.R;
import com.atguigu.srb.base.utils.JwtUtils;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.pojo.entity.LendReturn;
import com.atguigu.srb.core.service.LendReturnService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 还款记录表 前端控制器
 * </p>
 *
 * @author tjf
 * @since 2022-01-03
 */
@RestController
@Slf4j
@Api(tags = "还款计划")
@RequestMapping("/api/core/lendReturn")
public class LendReturnController {
    private final LendReturnService lendReturnService;

    public LendReturnController(LendReturnService lendReturnService) {
        this.lendReturnService = lendReturnService;
    }

    @ApiOperation("获取列表")
    @GetMapping("/list/{lendId}")
    public R list(@ApiParam("标的id") @PathVariable Long lendId) {
        List<LendReturn> list = lendReturnService.selectByLendId(lendId);
        return R.ok().data("list", list);
    }

    @ApiOperation("用户还款")
    @PostMapping("/auth/commitReturn/{lendReturnId}")
    public R commitReturn(@ApiParam(value = "还款计划id", required = true) @PathVariable Long lendReturnId, @RequestHeader String token) {
        Long userId = JwtUtils.getUserId(token);
        String formStr = lendReturnService.commitReturn(lendReturnId, userId);
        return R.ok().data("formStr", formStr);
    }

    @ApiOperation("用户还款异步回调接口")
    @PostMapping("/notifyUrl")
    public String notifyUrl(HttpServletRequest httpServletRequest) {
        // 获取汇付宝回调时携带的参数
        Map<String, Object> map = RequestHelper.switchMap(httpServletRequest.getParameterMap());
        log.info("还款异步回调接收参数如下：" + JSON.toJSONString(map));

        // 校验签名
        if (!RequestHelper.isSignEquals(map)) {
            log.error("用户账户绑定异步回调签名验证错误：" + JSON.toJSONString(map));
            return "fail";
        }

        if ("0001".equals(map.get("resultCode"))) {
            log.info("验证签名成功，开始充值账户");

            return lendReturnService.notify(map);

        }
        return "success";
    }
}

